/**
 * 
 */
package es.ibm.santillana.mdm.common.bussinesmodel;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import com.ibm.pim.attribute.AttributeInstance;
import com.ibm.pim.attribute.ExtendedAttributeChanges;
import com.ibm.pim.catalog.Catalog;
import com.ibm.pim.catalog.CatalogManager;
import com.ibm.pim.catalog.item.BaseItem;
import com.ibm.pim.catalog.item.Item;
import com.ibm.pim.collaboration.CollaborationItem;
import com.ibm.pim.collection.PIMCollection;
import com.ibm.pim.common.exceptions.PIMInternalException;
import com.ibm.pim.common.exceptions.PIMInvalidPathException;
import com.ibm.pim.common.exceptions.PIMSearchException;
import com.ibm.pim.context.Context;
import com.ibm.pim.context.PIMContextFactory;
import com.ibm.pim.extensionpoints.CollaborationItemPrePostProcessingFunctionArguments;
import com.ibm.pim.hierarchy.Hierarchy;
import com.ibm.pim.hierarchy.HierarchyManager;
import com.ibm.pim.hierarchy.category.Category;
import com.ibm.pim.lookuptable.LookupTable;
import com.ibm.pim.lookuptable.LookupTableEntry;
import com.ibm.pim.lookuptable.LookupTableManager;
import com.ibm.pim.organization.Organization;
import com.ibm.pim.organization.Role;
import com.ibm.pim.organization.User;
import com.ibm.pim.organization.UserSetting;
import com.ibm.pim.search.SearchQuery;
import com.ibm.pim.search.SearchResultSet;
import com.ibm.pim.spec.SecondarySpec;
import com.ibm.pim.spec.Spec;
import com.ibm.pim.spec.SpecManager;
import com.ibm.pim.utils.Logger;

import es.ibm.santillana.mdm.common.util.ConstSantillana;
import es.ibm.santillana.mdm.common.util.SantillanaLogger;

/**
 * This class implemented the design decission
 * based of diferents relations betwen objets.
 * Configure the bussines model based in MDM Collab Server
 * @version 1.0, 29/04/2014
 * @author Benito Perez
 */
public class  ConfigModel {

	/**
	 * 
	 */
	public ConfigModel() {
		
	}
	
	/** 
     * Get the diferents autors of a article
     * @param itm Article
     * @return List of autors.
     */
	public static List <Item> getAutorsByArticle(Item article) {
		
		List <Item> listaAutores = new ArrayList<Item>();
		AttributeInstance attInstance = article.getAttributeInstance("Articulos CPS/Autores");
		int numAutores = attInstance.getChildren().size();
		for (int i = 0; i < numAutores; i ++) {
			listaAutores.add(article.getAttributeInstance("Articulos CPS/Autores#" + i +"/Autor").getLinkedItem());
			
		}
		return listaAutores;
		
	}
	
	
	/** 
     * Get the names of diferents countries that an article is mapped
     * 
     * Important: Now the languaje name is selection with local of current user
     * 
     * @param itm Article
     * @return List of country.
     */
	public static List <String> getCountryNamesByArticle(Item article) {
		List <String> countryNameList = new ArrayList<String>();
		List <Category> listCountries = getCountriesByArticle(article);
		String locale = PIMContextFactory.getCurrentContext().getCurrentUser().getUserSettingValue(UserSetting.ITEM_CATEGORY_DISPLAY_LOCALE);
		for(Category country:listCountries) {
			countryNameList.add((String) country.getAttributeValue("Geographies HPS/Display Name/"+ locale));
		}
		return countryNameList;
		
	}
	
	
	/** 
     * Get the diferents countries where an article is mapped
     * @param itm Article
     * @return List of countrys.
     */
	public static List <Category> getCountriesByArticle(Item article) {
		
		List <Category> countryList = new ArrayList<Category>();
		HierarchyManager hiMng = PIMContextFactory.getCurrentContext().getHierarchyManager();
		Hierarchy Hicountries = hiMng.getHierarchy("Geographies");
		Collection <Category> collCountrys =  article.getCategories(Hicountries);
		Iterator <Category> it = collCountrys.iterator();

		while (it.hasNext()) {
			countryList.add(it.next());
			
		}
		
		return countryList;
	}
	
	/** 
     * Get the secondary spec mapped to item according with the Tipo de Producto
     * @param itm Article
     * @return name of secondary spec.
     */
	public static String getSecondarySpecFromProductType(Item article) {
		
		HierarchyManager hiMng = PIMContextFactory.getCurrentContext().getHierarchyManager();
		Hierarchy HiTP = hiMng.getHierarchy(ConstSantillana.JERARQUIA_TIPO_DE_PRODUCTO);
		
		Collection <Category> collTP =  article.getCategories(HiTP);
		Iterator <Category> it = collTP.iterator();
		String secSpecName = "";
		if (it.hasNext()) {
			Collection <SecondarySpec> secSpecs =  it.next().getItemSecondarySpecs();
			if (secSpecs != null){
				secSpecName = secSpecs.iterator().next().getName();
			}
		
		}
		
		return secSpecName;
	}
	
	/** 
     * Get the secondary spec mapped to item according with the Tipo de Producto
     * @param itm Article
     * @return name of secondary spec.
     */
	public static String getSecondarySpecFromProductType(CollaborationItem article) {
		
		Collection <Category> collTP =  article.getCategories();
		Iterator <Category> it = collTP.iterator();
		String secSpecName = "";
		while (it.hasNext()) {
			Category cat = it.next();
			String hierarchyName = cat.getHierarchy().getName();
			if (hierarchyName.equals(ConstSantillana.JERARQUIA_TIPO_DE_PRODUCTO)){
				
				Collection<SecondarySpec> secSpecs = cat.getItemSecondarySpecs();
				if (secSpecs != null && secSpecs.size() > 0){
					secSpecName = secSpecs.iterator().next().getName();
				}else{
					secSpecName = "";
				}
				break;
			}
		
		}
		return secSpecName;
	}
	
	
	/** 
	 * Get the product type specs mapped to item according with the Tipo de Producto
	 * @param itm Article
	 * @return HashMap with the spec names.
	 */
	public static HashMap<String, String> getProductTypeSpecNames(CollaborationItem itm) {
		
		HashMap<String, String> hmSpecNames = new HashMap<String, String>();
		Collection <Category> collTP =  itm.getCategories();
		Iterator <Category> it = collTP.iterator();
		
		String specName = "";
		while (it.hasNext()) {
			Category cat = it.next();
			String hierarchyName = cat.getHierarchy().getName();
			if (hierarchyName.equals(ConstSantillana.JERARQUIA_TIPO_DE_PRODUCTO)){
				
				Collection<SecondarySpec> secSpecs = cat.getItemSecondarySpecs();
				Iterator<SecondarySpec> itSpec = secSpecs.iterator();
				while (itSpec.hasNext()){
					specName = itSpec.next().getName();
					String specKey = specName.split("-")[1].trim();
					hmSpecNames.put(specKey, specName);
						
				}
			}
		
		}
		
		return hmSpecNames;
		
	}

	/** 
     * Get the secondary spec names mapped to item according with the Sociedades
     * @param itm Article
     * @return name of secondary spec.
     */
	public static List<String> getSecondarySpecFromSociedades(Item article) {
		
		HierarchyManager hiMng = PIMContextFactory.getCurrentContext().getHierarchyManager();
		Hierarchy HiSoc = hiMng.getHierarchy(ConstSantillana.JERARQUIA_SOCIEDADES);
		
		List<String> secSpecNameList = new ArrayList<String>(); 
		
		Collection <Category> collSoc =  article.getCategories(HiSoc);
		Iterator <Category> it = collSoc.iterator();
		if (it.hasNext()) {
			secSpecNameList.add((String)it.next().getItemSecondarySpecs().iterator().next().getName());
		
		}
		
		return secSpecNameList;
	}
	
	/** 
     * Get the secondary spec names mapped to item according with the Sociedades
     * @param itm Article
     * @return name of secondary spec.
     */
	public static List<SecondarySpec> getSecondarySpecFromSociedadesTipo(CollaborationItem article) {
		
		List<SecondarySpec> listSpecs = new ArrayList<SecondarySpec>();
		Collection <Category> collTP =  article.getCategories();
		Iterator <Category> it = collTP.iterator();
		
		while (it.hasNext()) {
			Category cat = it.next();
			String hierarchyName = cat.getHierarchy().getName();
			if (hierarchyName.equals(ConstSantillana.JERARQUIA_SOCIEDADES)){
				
				Collection<SecondarySpec> secSpecs = cat.getItemSecondarySpecs();
				Iterator<SecondarySpec> itSpec = secSpecs.iterator();
				while (itSpec.hasNext()){
					
					listSpecs.add(itSpec.next());
						
				}
			}
		
		}
		
		return listSpecs;
		
	}
	
	/** 
     * check if the item has a relation type personalizacion de
     * @param itm Article
     * @return boolean
     */
	public static boolean isPersonalizacion(ArrayList<String> secSpecList, CollaborationItem itm, String pathCode, String code) {
		
		
		Iterator <String> it = secSpecList.iterator();
		while (it.hasNext()) {
			String secSpecName = it.next();
			AttributeInstance attIn = itm.getAttributeInstance(secSpecName+ConstSantillana.ARTICULOS_RELACIONADOS);
			List<? extends AttributeInstance> relationList = attIn.getChildren();
			if ((relationList.size() > 0) ){
				Iterator<? extends AttributeInstance> itRel = relationList.iterator();
				while(itRel.hasNext()){
					AttributeInstance childRel = itRel.next();
					String path = childRel.getPath();
					AttributeInstance attRel = itm.getAttributeInstance(path+ConstSantillana.TIPO_RELACION);
					String relation = (String) attRel.getValue();
					
					if (relation != null && relation.equals(ConstSantillana.RELACION_PERSONALIZACION)){
						AttributeInstance attItm = itm.getAttributeInstance(path+ConstSantillana.ARTICULO_RELACIONADO);
						Item itmRel = (Item) attItm.getValue();
						String isbnRel = (String) itmRel.getAttributeValue(pathCode);
						if (isbnRel != null && !isbnRel.equals("") && isbnRel.equals(code)){
							return true;
						}
					}
				}
			}
		}
		
		return false;
	}
	
	
	
	public static String[] getAuxiliarCatalogs() {
		Context ctx = PIMContextFactory.getCurrentContext();
		CatalogManager ctgMng = ctx.getCatalogManager();
		Collection <Catalog> col =  ctgMng.getCatalogs();
	
		int conta =  0;
		ArrayList <String> result = new ArrayList<String>();
		for (Catalog ctg:col) {
			if (ctg.getAccessControlGroup().getName().equals("Auxiliares ACG")){
				result.add(ctg.getName());
			}
		}
		String [] catalogosAux = new String [result.size()];
	
		for (String nameCtg:result) {
			catalogosAux[conta] = nameCtg;
			conta++;
		}
		
		
		return catalogosAux;
	}
	
	/** 
     * Get the user country
     * @param user 
     * @return name of secondary spec.
     */
	public static String getCountryCodeFromUser(User user) {
		
		Context ctx = PIMContextFactory.getCurrentContext();
		LookupTableManager lkpMng = ctx.getLookupTableManager();
		
		LookupTable lkp = lkpMng.getLookupTable("Code_Country");
		PIMCollection <LookupTableEntry> colLkpEntry = lkp.getLookupTableEntries();
		
		PIMCollection <Role> collRole = user.getRoles();
		for(LookupTableEntry entry:colLkpEntry) {
			String sRole = entry.getKey();
			for (Role roleUser:collRole){
				String sName = roleUser.getName();
				if (sName.equals(sRole)) {
					return (String) entry.getAttributeValue(ConstSantillana.SPEC_USER_CODE + "/CountryCode");
				}
			}
		}
		return null;
	}
		
		public static String getCountrysCodeFromUser(User user) {
			
			Context ctx = PIMContextFactory.getCurrentContext();
			LookupTableManager lkpMng = ctx.getLookupTableManager();
			
			LookupTable lkp = lkpMng.getLookupTable("Code_Country");
			PIMCollection <LookupTableEntry> colLkpEntry = lkp.getLookupTableEntries();
			String sCountryCode = new String();
			System.out.println(user.getUserName());
			PIMCollection <Role> collRole = user.getRoles();
			for(LookupTableEntry entry:colLkpEntry) {
				String sRole = entry.getKey();
				for (Role roleUser:collRole){
					String sName = roleUser.getName();
					System.out.println("Rol del usuario: " + sName);
					if (sName.equals(sRole)) {
						sCountryCode = sCountryCode + ";" + (String) entry.getAttributeValue(ConstSantillana.SPEC_USER_CODE + "/CountryCode");
					}
				}
			}
		
		//TODO: Menuda maravilla
//		if ("hola".equals("hola")) {
//			return "CO";
//		}
//		else {
//			Collection<Organization> orgList = user.getOrganizations();
//			Iterator<Organization> itOrg = orgList.iterator();
//			while (itOrg.hasNext()){
//				Organization org = itOrg.next();
//				String orgName = org.getHierarchy().getName();
//				
//				if (orgName.equals(ConstSantillana.JERARQUIA_PAISES_USUARIOS)){
//					String countryCode = (String) org.getAttributeValue("");
//				}
//			}
//		}

		System.out.println(sCountryCode);
		return sCountryCode;
	}
	
	public static String getCountryCodeFromUser() {
		return "MX";
	}
	
	/** 
     * Get the global specific spec for a country
     * @param country code
     * @return name of secondary spec.
     */
	public static ArrayList<String> getGlobalSpecificSpecForCountry(String countryCode) {
		
		HierarchyManager hiMng = PIMContextFactory.getCurrentContext().getHierarchyManager();
		Hierarchy hi = hiMng.getHierarchy(ConstSantillana.JERARQUIA_SOCIEDADES);
		ArrayList<String> secSpecNameList = new ArrayList<String>();
		Category cat = hi.getCategoryByPrimaryKey(countryCode);
		
		Collection <Category> colChildren = cat.getChildren();
		if (colChildren!=null){
			Iterator <Category> it = colChildren.iterator();
			while (it.hasNext()){
				Category catHija = it.next();
				secSpecNameList.add((String) catHija.getItemSecondarySpecs().iterator().next().getName());
			}
		}
		
		
		return secSpecNameList;
	}
	
	/** 
     * Get the product types categories names
     * @param user 
     * @return array with the categories names.
     */
	public static String[] getTipoDeProductoCategories(Hierarchy hiTypes){
		
		//Obtenemos las ediciones pertenecientes al pais		
		PIMCollection<Category> collItems =  hiTypes.getCategoriesAtLevel(1);
		Iterator <Category> it = collItems.iterator();
		String[] namesList = new String[collItems.size()];
		String name = "";
		int i= 0;
		while (it.hasNext()) {
			Category cat = it.next();
			
		
				name = (String) cat.getPrimaryKey() + " - " +(String) cat.getAttributeValue(ConstSantillana.TIPO_DE_PRODUCTO_NAME);
				namesList[i] = name;
				i++;
		}
		
		return namesList;
	}
	
	/** 
     * Get the sociedades belonging to a country
     * @param user 
     * @return array with the categories names.
     */
	public static String[] getSociedadesByCountry(String sCountry) {
		
		
		HierarchyManager hiMng = PIMContextFactory.getCurrentContext().getHierarchyManager();
		Hierarchy hiCountries = hiMng.getHierarchy(ConstSantillana.JERARQUIA_SOCIEDADES);
		Category ctyCountry = hiCountries.getCategoryByPrimaryKey(sCountry);
		
		//Obtenemos las ediciones pertenecientes al pais		
		Collection<Category> collCats =  ctyCountry.getChildren();
		Iterator <Category> it = collCats.iterator();
		String[] editorialList = new String[collCats.size()];
		int i = 0;
		while (it.hasNext()) {
			Category cat = it.next();
			editorialList[i] = (String) cat.getPrimaryKey() + " - " +(String) cat.getAttributeValue(ConstSantillana.SOCIEDADES_NAME);
			i++;
		}
		
		return editorialList;
	}
	
	/** 
     * Get the sociedades belonging to a country
     * @param user 
     * @return array with the categories names.
     */
	public static String[] getSociedades() {
		
		
		HierarchyManager hiMng = PIMContextFactory.getCurrentContext().getHierarchyManager();
		Hierarchy hiCountries = hiMng.getHierarchy(ConstSantillana.JERARQUIA_SOCIEDADES);
		
		//Obtenemos las ediciones pertenecientes al pais		
		Collection<Category> collCats =   hiCountries.getCategoriesAtLevel(2);
		Iterator <Category> it = collCats.iterator();
		String[] editorialList = new String[collCats.size()];
		int i = 0;
		while (it.hasNext()) {
			Category cat = it.next();
			editorialList[i] = (String) cat.getPrimaryKey() + " - " +(String) cat.getAttributeValue(ConstSantillana.SOCIEDADES_NAME);
			i++;
		}
		
		return editorialList;
	}
	
	
	
	/** 
     * Get the sociedades belonging to a country
     * @param user 
     * @return array with the categories names.
     */
	public static String[] getEmpresasEditoras(String catalogoName) {
		
				
		Context ctxPIM = PIMContextFactory.getCurrentContext();
		String[] valuesList = null;
		try{
			
			int i = 0;
			//Obtenemos las ediciones pertenecientes al pais		
			String sQuery = "select item.pk, item['Tabla Especifica/Valor/es_ES'] from catalog('"+catalogoName+"') " +
					" where item['Tabla Especifica/Visible'] = true";
			SearchQuery searchQ = ctxPIM.createSearchQuery(sQuery);
			SearchResultSet resSet = searchQ.execute();
			valuesList = new String[resSet.size() + 1];
			while(resSet.next()){
			
				String pk = resSet.getString(1);
				String name = resSet.getString(2);
				valuesList[i] = pk + " - " + name;
				i++;
			}
			valuesList[i] = "";
		}catch(PIMSearchException pse){
			pse.printStackTrace();
		}
		return valuesList;
	}
	
	/**
	 * @param pais
	 * @return
	 */
	public static Collection<Category> getSociedadesNameByCountry(String paises) {			
		System.out.println("Paises: " + paises);
		HierarchyManager hiMng = PIMContextFactory.getCurrentContext().getHierarchyManager();
		Hierarchy hiSociedades = hiMng.getHierarchy(ConstSantillana.JERARQUIA_PAISES);
		String[] aPaises = paises.split(";");
		ArrayList<Category> result = new ArrayList<Category>();
		for (int i = 1; i < aPaises.length; i++) {
			
		
			String pais =  aPaises[i];
			System.out.println(pais);
			Category catSociedades = hiSociedades.getCategoryByPrimaryKey(pais);
			Collection<Category> categorias =  catSociedades.getChildren();
			result.addAll(categorias);
		}
		
		
		//Obtenemos las categorias de la jerarquia Sociedad pertenecientes al pais		
		
		
		return result;
	}
	/** 
     * Get the authors from the catalog
     * @param user 
     * @return array with the author names.
     */
	public static String[] getAutores()  {
		
		//TODO: Adaptar funcion al modelo final
		
		Context ctxPIM = PIMContextFactory.getCurrentContext();
		String[] autorList = null;
		try{
		
			//Obtenemos las ediciones pertenecientes al pais		
			String sQuery = "select item['Tabla Global/Valor'] from catalog('Sellos') ";
			SearchQuery searchQ = ctxPIM.createSearchQuery(sQuery);
			SearchResultSet resSet = searchQ.execute();
			int i = 0;
			autorList = new String[resSet.size()];
			while(resSet.next()){
				
				autorList[i] = resSet.getString(1);
				i++;
			}
		}catch(PIMSearchException pse){
			pse.printStackTrace();
		}
		return autorList;	
		
	}

	public static String getSecondarySpecFromSociedades(
			CollaborationItem collabitem) {

		
		
		Collection <Category> collTP =  collabitem.getCategories();
		Iterator <Category> it = collTP.iterator();
		String secSpecName = "";
		while (it.hasNext()) {
			Category cat = it.next();
			String hierarchyName = cat.getHierarchy().getName();
			if (hierarchyName.equals(ConstSantillana.JERARQUIA_SOCIEDADES)){
				secSpecName = cat.getItemSecondarySpecs().iterator().next().getName();
				return secSpecName;
				
			}
		
		}
		return secSpecName;
		
	}
	
	/** 
     * Get the secondary spec names mapped to item according with the Sociedades
     * @param itm Article
     * @return name of secondary spec.
     */
	public static ArrayList<String> getSecondarySpecListFromSociedades(CollaborationItem article) {
		
		
		ArrayList<String> secSpecNameList = new ArrayList<String>(); 
		
		Collection <Category> collSoc =  article.getCategories();
		Iterator <Category> it = collSoc.iterator();
		while (it.hasNext()) {
			Category cat = it.next();
			String hierarchyName = cat.getHierarchy().getName();
			if (hierarchyName.equals(ConstSantillana.JERARQUIA_PAISES)){
				String name = (String) cat.getItemSecondarySpecs().iterator().next().getName();
				if (!name.contains("SEARCH")){
					secSpecNameList.add(name);
				}
			}
		
		}
		
		return secSpecNameList;
	}
	/** 
     * Get the secondary spec names mapped to item according with the Sociedades_Tipo category  and user country
     * @param Collaboration itm Article
     * @param String user country
     * @return name of secondary spec.
     */
	public static ArrayList<String> getSecondarySpecListFromSociedadesTypeByCountry(CollaborationItem article, String country) {
		
		
		ArrayList<String> secSpecNameList = new ArrayList<String>(); 
		
		Collection <Category> collSoc =  article.getCategories();
		Iterator <Category> it = collSoc.iterator();
		while (it.hasNext()) {
			Category cat = it.next();
			String hierarchyName = cat.getHierarchy().getName();
			if (hierarchyName.equals(ConstSantillana.JERARQUIA_SOCIEDADES)){
				String catCountry = cat.getParent().getParent().getPrimaryKey();
				if (catCountry.equals(country)){
					Collection <SecondarySpec> colSpec = cat.getItemSecondarySpecs();
					if (colSpec == null || colSpec.size() == 0 ) {
						//Ver que pasa en esta situacion
					}
					else {
						secSpecNameList.add((String) cat.getItemSecondarySpecs().iterator().next().getName());
					}
					
				}
			}
		
		}
		
		return secSpecNameList;
	}
	
	/** 
     * Get the secondary spec names mapped to item according with the Sociedades_Tipo category  and user country
     * @param Collaboration itm Article
     * @param String user country
     * @return name of secondary spec.
     */
	public static ArrayList<String> getSecondarySpecListFromSociedadesTypeByCountry(Item article, String country) {
		
		
		ArrayList<String> secSpecNameList = new ArrayList<String>(); 
		
		Collection <Category> collSoc =  article.getCategories();
		Iterator <Category> it = collSoc.iterator();
		while (it.hasNext()) {
			Category cat = it.next();
			String hierarchyName = cat.getHierarchy().getName();
			if (hierarchyName.equals(ConstSantillana.JERARQUIA_SOCIEDADES)){
				String catCountry = cat.getParent().getParent().getPrimaryKey();
				if (catCountry.equals(country)){
					secSpecNameList.add((String) cat.getItemSecondarySpecs().iterator().next().getName());
				}
			}
		
		}
		
		return secSpecNameList;
	}
	
	/** 
     * Get the secondary spec names mapped to item according with the Sociedades  and user country
     * @param Collaboration itm Article
     * @param String user country
     * @return name of secondary spec.
     */
	public static ArrayList<String> getSecondarySpecListFromSociedadesByCountry(CollaborationItem article, String country) {
		
		
		ArrayList<String> secSpecNameList = new ArrayList<String>(); 
		
		Collection <Category> collSoc =  article.getCategories();
		Iterator <Category> it = collSoc.iterator();
		while (it.hasNext()) {
			Category cat = it.next();
			String hierarchyName = cat.getHierarchy().getName();
			if (hierarchyName.equals(ConstSantillana.JERARQUIA_SOCIEDADES)){
				String catCountry = cat.getParent().getParent().getPrimaryKey();
				if (catCountry.equals(country)){
					secSpecNameList.add((String) cat.getParent().getItemSecondarySpecs().iterator().next().getName());
				}
			}
		
		}
		
		return secSpecNameList;
	}
	
	public static ArrayList<Category> getSociedadCategoryListFromSociedadesByCountry(CollaborationItem article, String country) {
		System.out.println("getSociedadCategoryListFromSociedadesByCountry");
		
		ArrayList<Category> listCategorys = new ArrayList<Category>(); 
		
		Collection <Category> collSoc =  article.getCategories();
		Iterator <Category> it = collSoc.iterator();
		while (it.hasNext()) {
			Category cat = it.next();
			String hierarchyName = cat.getHierarchy().getName();
			System.out.println(hierarchyName);
			if ( hierarchyName.equals(ConstSantillana.JERARQUIA_PAISES)){
				System.out.println(cat.getPrimaryKey());
				String catCountry = cat.getParent().getPrimaryKey();
				if (catCountry.equals(country)){
					listCategorys.add(cat);
					System.out.println(cat.getDisplayName());
				}
			}
		
		}
		
		return listCategorys;
	}
	
	/** 
     * Get the secondary spec names mapped to item according with the Sociedades  and user country
     * @param itm Article
     * @param String user country
     * @return name of secondary spec.
     */
	public static ArrayList<String> getSecondarySpecListFromSociedadesByCountry(Item article, String country) {
		
		
		ArrayList<String> secSpecNameList = new ArrayList<String>(); 
		
		Collection <Category> collSoc =  article.getCategories();
		Iterator <Category> it = collSoc.iterator();
		while (it.hasNext()) {
			Category cat = it.next();
			String hierarchyName = cat.getHierarchy().getName();
			if (hierarchyName.equals(ConstSantillana.JERARQUIA_SOCIEDADES)){
				String catCountry = cat.getParent().getParent().getPrimaryKey();
				if (catCountry.equals(country)){
					secSpecNameList.add((String) cat.getParent().getItemSecondarySpecs().iterator().next().getName());
				}
			}
		
		}
		
		return secSpecNameList;
	}

	/** 
     * Get values of the catalogo specified for the country specified
     * @param country identifier 
     * @param catalog name 
     * @return array with the author names.
     */
	public static String[] getCatalogValuesByCountry(String country,
			String catalogoName) {
		
		Context ctxPIM = PIMContextFactory.getCurrentContext();
		String[] valuesList = null;
		try{
			
			int i = 0;
			//Obtenemos las ediciones pertenecientes al pais		
			String sQuery = "select item['Tabla Especifica/Valor/es_ES'] from catalog('"+catalogoName+"') " +
					" where (item['Tabla Especifica/Pais'] ='"+country+"' or item['Tabla Especifica/Pais'] ='GL') and item['Tabla Especifica/Visible'] = true";
			SearchQuery searchQ = ctxPIM.createSearchQuery(sQuery);
			SearchResultSet resSet = searchQ.execute();
			valuesList = new String[resSet.size()];
			while(resSet.next()){
			
				valuesList[i] = resSet.getString(1);;
				i++;
			}
		
		}catch(PIMSearchException pse){
			pse.printStackTrace();
		}
		return valuesList;
	}
	
	/** 
     * Get values of the catalogo specified que sean visibles
     * @param catalog name 
     * @return array with the author names.
     */
	public static String[] getVisibleCatalogValues(String catalogoName) {
		
		Context ctxPIM = PIMContextFactory.getCurrentContext();
		String[] valuesList = null;
		try{
			
			int i = 0;
			String sQuery = null;
			//Obtenemos las ediciones pertenecientes al pais
			if (catalogoName.equals("Lineas") || catalogoName.equals("Vida_Util")|| catalogoName.equals("Ediciones")) {
				sQuery = "select item['Tabla Global/Valor/es_ES'] from catalog('"+catalogoName+"') " +
						" where item['Tabla Global/Visible'] = true order by item['Tabla Global/Code'] ";
			}
			else {
				sQuery = "select item['Tabla Global/Valor/es_ES'] from catalog('"+catalogoName+"') " +
						" where item['Tabla Global/Visible'] = true";
			}
			SearchQuery searchQ = ctxPIM.createSearchQuery(sQuery);
			SearchResultSet resSet = searchQ.execute();
			valuesList = new String[resSet.size() + 2];
			while(resSet.next()){
			
				valuesList[i] = resSet.getString(1);;
				i++;
			}
			valuesList[i] = " ";
			valuesList[i + 1] = "";
			
		}catch(PIMSearchException pse){
			pse.printStackTrace();
		}
		
		return valuesList;
	}
	
	
	/** 
     * Get values of the catalogo specified que sean visibles
     * @param catalog name 
     * @return array with the author names.
     */
	public static String[] getTemasTransversales(String catalogoName, String linea) {
		
		Context ctxPIM = PIMContextFactory.getCurrentContext();
		String[] valuesList = null;
		try{
			
			int i = 0;
			//Obtenemos las ediciones pertenecientes al pais		
			String sQuery = "select item['Temas_Transversales/Valor/es_ES'] from catalog('"+catalogoName+"') " +
					" where item['Temas_Transversales/Visible'] = true";
			if (linea != null && !linea.equals("")){
				Item itmLinea = getGlobalItemByName(linea, ConstSantillana.CATALOGO_LINEAS);
				if (itmLinea != null){
					sQuery = sQuery + " and item['Temas_Transversales/Code_Linea'].pk ='"+itmLinea.getPrimaryKey()+"'";
				}
			}
			SearchQuery searchQ = ctxPIM.createSearchQuery(sQuery);
			SearchResultSet resSet = searchQ.execute();
			valuesList = new String[resSet.size() + 2];
			while(resSet.next()){
			
				valuesList[i] = resSet.getString(1);;
				i++;
			}
			valuesList[i] = " ";
			valuesList[i + 1] = "";
			
		}catch(PIMSearchException pse){
			pse.printStackTrace();
		}
		
		return valuesList;
	}
	
	/** 
     * Get values of the catalogo specified que sean visibles
     * @param catalog name 
     * @return array with the author names.
     */
	public static String[] getVisiblePaisesValues(String catalogoName) {
		
		Context ctxPIM = PIMContextFactory.getCurrentContext();
		String[] valuesList = null;
		try{
			
			int i = 0;
			//Obtenemos las ediciones pertenecientes al pais		
			String sQuery = "select item['Paises/Valor/es_ES'] from catalog('"+catalogoName+"') " +
					" where item['Paises/Visible'] = true";
			SearchQuery searchQ = ctxPIM.createSearchQuery(sQuery);
			SearchResultSet resSet = searchQ.execute();
			valuesList = new String[resSet.size()];
			while(resSet.next()){
			
				valuesList[i] = resSet.getString(1);;
				i++;
			}
		
		}catch(PIMSearchException pse){
			pse.printStackTrace();
		}
		return valuesList;
	}
	/** 
     * Get values of the catalogo specified que sean visibles
     * @param catalog name 
     * @return array with the author names.
     */
	public static String[] getVisibleEstructuraAnaliticaValues(String catalogoName) {
		
		Context ctxPIM = PIMContextFactory.getCurrentContext();
		String[] valuesList = null;
		try{
			
			int i = 0;
			//Obtenemos las ediciones pertenecientes al pais		
			String sQuery = "select item['Estructura_Analitica/Valor'] from catalog('"+catalogoName+"') " +
					" where item['Estructura_Analitica/Visible'] = true";
			SearchQuery searchQ = ctxPIM.createSearchQuery(sQuery);
			SearchResultSet resSet = searchQ.execute();
			valuesList = new String[resSet.size()];
			while(resSet.next()){
			
				valuesList[i] = resSet.getString(1);;
				i++;
			}
		
		}catch(PIMSearchException pse){
			pse.printStackTrace();
		}
		return valuesList;
	}
	
	
	/** 
     * Get values of the catalogo specified que sean visibles
     * @param catalog name 
     * @return array with the author names.
     */
	public static String[] getPaisesJerarquiaValues() {
		
		Context ctxPIM = PIMContextFactory.getCurrentContext();
		String[] valuesList = null;
		int i = 0;
			
		HierarchyManager hyMng = ctxPIM.getHierarchyManager();
		Hierarchy hy = hyMng.getHierarchy("Paises");
		PIMCollection <Category> list = hy.getCategories();
		valuesList = new String[list.size()];
		for (Category cat:list) {
			valuesList[i] = cat.getPrimaryKey();
			i++;
		}
		
		
		return valuesList;
	}
	
	
	/** 
     * Get values of the catalogo specified que sean visibles
     * @param catalog name 
     * @return array with the author names.
     */
	public static String[] getVisibleFechasConmemorativasValues(String catalogoName, String country) {
		
		Context ctxPIM = PIMContextFactory.getCurrentContext();
		String[] valuesList = null;
		try{
			
			int i = 0;
			//Obtenemos las ediciones pertenecientes al pais		
			String sQuery = "select item['Fechas_Conmemorativas/Valor/es_ES'] from catalog('"+catalogoName+"') " +
					" where item['Fechas_Conmemorativas/Pais'] = 'GL' or item['Fechas_Conmemorativas/Pais']='"+country+"'";
			SearchQuery searchQ = ctxPIM.createSearchQuery(sQuery);
			SearchResultSet resSet = searchQ.execute();
			valuesList = new String[resSet.size()];
			while(resSet.next()){
			
				valuesList[i] = resSet.getString(1);
				i++;
			}
		
		}catch(PIMSearchException pse){
			pse.printStackTrace();
		}
		return valuesList;
	}
	
	public static Spec transformaSpec (String sName)  {
		
		
		String strozo1 = sName.split("-")[0];
		String strozo2 = sName.split("-")[1];
		String strozo3 = sName.split("-")[2];
		String sResult = strozo1 + "-" + strozo2 + "-" + strozo3; 
		System.out.println("PRUEBAS INTEGRACION sResult: " + sResult);
		Context ctxPIM = PIMContextFactory.getCurrentContext();
		SpecManager spcMng = ctxPIM.getSpecManager();
		Spec spec = spcMng.getSpec(sResult + "SEARCH");
		return spec;
	    
		
	}
	
	/** 
     * Get the item of the catalog specified
     * @param String item pk
     * @param String catalog name
     * @return item if exists, null otherwise
     */
	public static Item getItemFromCatalog(String pk, String catalogoName) {
		
		Context ctxPIM = PIMContextFactory.getCurrentContext();
		CatalogManager ctgMan = ctxPIM.getCatalogManager();
		Catalog ctg = ctgMan.getCatalog(catalogoName);
		if (pk != null && !pk.equals("")){
			Item itm = ctg.getItemByPrimaryKey(pk);
		
			return itm;
		}else{
			return null;
		}
	}
	
	/** 
     * format a date according with the pattern
     * @param String date
     * @param String catalog name
     * @return item if exists, null otherwise
     */
	public static Date formatDate(String date, String pattern) {
		
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		try {
			sdf.setLenient(false);
			Date dt = sdf.parse(date);
			return dt;
		} catch (ParseException e) {
			return null;
		}
	}
	
	/** 
     * get the country code according with the Collaboration Area Name
     * @param String collaboration area name
     * @return String with country Code
     */
	public static String getCountryCodeFromColArea(String colAreaName) {
		
		if (colAreaName != null){
			if (colAreaName.contains("Argentina")){
				return "AR";
				
			}
			if (colAreaName.contains("Colombia")){
				return "CO";
			}
			if (colAreaName.contains("Chile")){
				return "CL";
				
			}
			if (colAreaName.contains("Mexico")){
				return "MX";
				
			}
		}
		return null;
	}
	
	/** 
     * get the collaboration area Name according with the country code
     * @return String collaboration area name
     * @param String with country Code
     */
	public static String getCreationColAreaFromCountry(String country) {
		
		if (country != null){
			if (country.equals("AR")){
				return ConstSantillana.COL_AREA_CREAR_AR;
				
			}
			if (country.equals("CO")){
				return ConstSantillana.COL_AREA_CREAR_COL;
			}
			if (country.equals("CL")){
				return ConstSantillana.COL_AREA_CREAR_CL;
				
			}
			if (country.equals("MX")){
				return ConstSantillana.COL_AREA_CREAR_MX;
				
			}
		}
		return null;
	}
	
	public static String checkString(String in){
		
		if (in == null){
			in = "";
		}else{
			in = in.trim();
		}
		return in;
	}

	public static void replicateAttributes(CollaborationItem itm,
			CollaborationItemPrePostProcessingFunctionArguments arg0) {
		System.out.println("Dentro de replicar atributos");
		CatalogManager caMan = PIMContextFactory.getCurrentContext().getCatalogManager();		
		ExtendedAttributeChanges achanges = itm.getAttributeChangesSinceLastSave();
		if (achanges!=null){
			List <? extends AttributeInstance > list = achanges.getModifiedAttributesWithNewData();
			Iterator<? extends AttributeInstance> it = list.iterator();
			while (it.hasNext()) {
				AttributeInstance attrib = it.next();
				/*System.out.println("Path: " + attrib.getPath());
				if (attrib.getPath().endsWith("ISBN")) {
					itm.setAttributeValue(ConstSantillana.MAESTRO_ARTICULOS_SPEC + "/ISBN", attrib.getValue());
				}*/
				
				if (attrib.getPath().endsWith("DESC_Fecha_Conmemorativa")) {
					String value = (String) attrib.getValue();
					if (value!=null){
						Catalog ctgFechas = caMan.getCatalog(ConstSantillana.CATALOGO_FECHAS_CONMEMORATIVAS);
						PIMCollection<Item> itmCol = ctgFechas.getItemsWithAttributeValue("Fechas_Conmemorativas/Valor/es_ES", value);
						Iterator<Item> itItm = itmCol.iterator();
						if (itItm.hasNext()){
							Item fecha = itItm.next();
							Date dt = (Date) fecha.getAttributeValue("Fechas_Conmemorativas/Fecha");
							itm.setAttributeValue(attrib.getParent().getPath()+"/DATE_Fecha_Conmemorativa", dt);
						}
					
					}
				}
				else {
					
					
					
				}
				
			}
		}
		
	}
	
	public static void replicateSearchAttributes(ArrayList<String> specLocalList, String country, CollaborationItem itm,
			CollaborationItemPrePostProcessingFunctionArguments arg0) {
		System.out.println("Dentro de replicar atributos");
		Logger log = SantillanaLogger.getLogger();
		log.logInfo("Dentro de replicar atributos");
		ExtendedAttributeChanges achanges = itm.getAttributeChangesSinceLastSave();
		if (achanges != null){
			List <? extends AttributeInstance > list = achanges.getModifiedAttributesWithNewData();
			Iterator<? extends AttributeInstance> it = list.iterator();
			while (it.hasNext()) {
				AttributeInstance attrib = it.next();
				log.logInfo("Path: " + attrib.getPath());
				Iterator<String> itSpec = specLocalList.iterator();
				while(itSpec.hasNext()){
					String sSpecName = itSpec.next();
					String specSearchName = sSpecName+" SEARCH";
					if (specSearchName!= null && !specSearchName.equals("")){
						
						if (attrib.getPath().endsWith("DESC_Asignatura")) {
							log.logInfo("asignatura cambiada");
							Item asig = getAsignaturaByName((String) attrib.getValue(), country);
							if (asig!= null){
								log.logInfo("asignatura encontrado");
								AttributeInstance attIn = itm.getAttributeInstance(specSearchName+"/Asignatura");
								attIn.setValue(asig);
							}
						}
						if (attrib.getPath().endsWith("DESC_Materia")) {
							log.logInfo("materia cambiada");
							Item materia = getMateriaByName((String) attrib.getValue(), country);
							if (materia!= null){
								log.logInfo("materia encontrado");
								AttributeInstance attIn = itm.getAttributeInstance(specSearchName+"/Materia");
								attIn.setValue(materia);
							}
						}
						if (attrib.getPath().endsWith("DESC_Curso")) {
							log.logInfo("Curso cambiada");
							Item curso = getCursoByName((String) attrib.getValue(), country);
							if (curso!= null){
								log.logInfo("materia encontrado");
								AttributeInstance attIn = itm.getAttributeInstance(specSearchName+"/Nivel_Escolar/Curso");
								attIn.setValue(curso);
							}
						}
						
					}
					
				}
			}
		}
		
	}
	
	public static void replicateAttributes(Item itm) {
		System.out.println("Dentro de replicar atributos");
		CatalogManager caMan = PIMContextFactory.getCurrentContext().getCatalogManager();		
		ExtendedAttributeChanges achanges = itm.getAttributeChangesComparedTo((BaseItem) itm.getCatalog().createItem());
		if (achanges!=null){
			List <? extends AttributeInstance > list = achanges.getModifiedAttributesWithNewData();
			Iterator<? extends AttributeInstance> it = list.iterator();
			while (it.hasNext()) {
				AttributeInstance attrib = it.next();
				/*System.out.println("Path: " + attrib.getPath());
				if (attrib.getPath().endsWith("ISBN")) {
					itm.setAttributeValue(ConstSantillana.MAESTRO_ARTICULOS_SPEC + "/ISBN", attrib.getValue());
				}*/
				
				if (attrib.getPath().endsWith("DESC_Fecha_Conmemorativa")) {
					String value = (String) attrib.getValue();
					if (value!=null){
						Catalog ctgFechas = caMan.getCatalog(ConstSantillana.CATALOGO_FECHAS_CONMEMORATIVAS);
						PIMCollection<Item> itmCol = ctgFechas.getItemsWithAttributeValue("Fechas_Conmemorativas/Valor/es_ES", value);
						Iterator<Item> itItm = itmCol.iterator();
						if (itItm.hasNext()){
							Item fecha = itItm.next();
							Date dt = (Date) fecha.getAttributeValue("Fechas_Conmemorativas/Fecha");
							itm.setAttributeValue(attrib.getParent().getPath()+"/DATE_Fecha_Conmemorativa", dt);
						}
					
					}
				}
				else {
					
					
					
				}
				
			}
		}
		
	}
	
	public static void replicateSearchAttributes(ArrayList<String> specLocalList, String country, Item itm) {
		System.out.println("Dentro de replicar atributos");
		Logger log = SantillanaLogger.getLogger();
		log.logInfo("Dentro de replicar atributos");
		ExtendedAttributeChanges achanges = itm.getAttributeChangesComparedTo((BaseItem) itm.getCatalog().createItem());
		if (achanges != null){
			List <? extends AttributeInstance > list = achanges.getModifiedAttributesWithNewData();
			Iterator<? extends AttributeInstance> it = list.iterator();
			while (it.hasNext()) {
				AttributeInstance attrib = it.next();
				log.logInfo("Path: " + attrib.getPath());
				Iterator<String> itSpec = specLocalList.iterator();
				while(itSpec.hasNext()){
					String sSpecName = itSpec.next();
					String specSearchName = sSpecName+" SEARCH";
					if (specSearchName!= null && !specSearchName.equals("")){
						
						if (attrib.getPath().endsWith("DESC_Asignatura")) {
							log.logInfo("asignatura cambiada");
							Item asig = getAsignaturaByName((String) attrib.getValue(), country);
							if (asig!= null){
								log.logInfo("asignatura encontrado");
								AttributeInstance attIn = itm.getAttributeInstance(specSearchName+"/Asignatura");
								attIn.setValue(asig);
							}
						}
						if (attrib.getPath().endsWith("DESC_Materia")) {
							log.logInfo("materia cambiada");
							Item materia = getMateriaByName((String) attrib.getValue(), country);
							if (materia!= null){
								log.logInfo("materia encontrado");
								AttributeInstance attIn = itm.getAttributeInstance(specSearchName+"/Materia");
								attIn.setValue(materia);
							}
						}
						if (attrib.getPath().endsWith("DESC_Curso")) {
							log.logInfo("Curso cambiada");
							Item curso = getCursoByName((String) attrib.getValue(), country);
							if (curso!= null){
								log.logInfo("materia encontrado");
								AttributeInstance attIn = itm.getAttributeInstance(specSearchName+"/Nivel_Escolar/Curso");
								attIn.setValue(curso);
							}
						}
						
					}
					
				}
			}
		}
		
	}
	
	/**
	 * get the specific spec for the sociedad category given
	 * @param Category cat
	 * @return String with the spec name
	 */
	public static String getSocietySpecificSpec(Category cat) {
		
		String specName = "";
		Collection<SecondarySpec> colSpec = cat.getItemSecondarySpecs();
		Iterator<SecondarySpec> it = colSpec.iterator();
		
		while (it.hasNext()){
			SecondarySpec secSpec = it.next();
			if (!secSpec.getName().contains("SEARCH")){
				return secSpec.getName();
			}
		}
		return specName;
	}
	/**
	 * get the search spec for the sociedad category given
	 * @param Category cat
	 * @return String with the spec name
	 */
	public static String getSearchSpec(Category cat) {
		
		String specName = "";
		Collection<SecondarySpec> colSpec = cat.getItemSecondarySpecs();
		Iterator<SecondarySpec> it = colSpec.iterator();
		
		while (it.hasNext()){
			SecondarySpec secSpec = it.next();
			if (secSpec.getName().contains("SEARCH")){
				return secSpec.getName();
			}
		}
		return specName;
	}
	/**
	 * get the country for SociedadTipo category
	 * @param Category cat
	 * @return boloean true if the user country is the same than the parent's category
	 */
	public static boolean isCountryUserFromSociedadTipoCategory(Category cat, String country) {
		
		Category catPadre = cat.getParent().getParent();
		if (catPadre.getLevels()[0] == 1){
			if (catPadre.getPrimaryKey().equals(country) ){
				return true;
			}
		}
		return false;
	}
	public static String[] getSeriesMetodosValuesByCountry(String pais,
			String catalogoSeriesMetodos, String linea) {

		
		Context ctxPIM = PIMContextFactory.getCurrentContext();
		String[] valuesList = null;
		try{
			
			int i = 0;
			//Obtenemos las ediciones pertenecientes al pais		
			String sQuery = "select item['Series_Metodos/Valor/es_ES'] from catalog('"+catalogoSeriesMetodos+"') " +
					" where (item['Series_Metodos/Pais'] ='"+pais+"' or item['Series_Metodos/Pais'] ='GL' and item['Series_Metodos/Visible'] = true)";
			if (linea != null && !linea.equals("")){
				Item itmLinea = getGlobalItemByName(linea, ConstSantillana.CATALOGO_LINEAS);
				if (itmLinea != null){
					sQuery = sQuery + " and item['Series_Metodos/Code_Linea'].pk ='"+itmLinea.getPrimaryKey()+"'";
				}
			}
			SearchQuery searchQ = ctxPIM.createSearchQuery(sQuery);
			SearchResultSet resSet = searchQ.execute();
			valuesList = new String[resSet.size()];
			while(resSet.next()){
			
				valuesList[i] = resSet.getString(1);;
				i++;
			}
		
		}catch(PIMSearchException pse){
			pse.printStackTrace();
		}
		return valuesList;
	
	}

	public static String[] getAsignaturasValuesByCountry(String pais,
			String catalogoAsignaturas) {
		
		Context ctxPIM = PIMContextFactory.getCurrentContext();
		String[] valuesList = null;
		try{
			
			int i = 0;
			//Obtenemos las ediciones pertenecientes al pais		
			String sQuery = "select item['Asignaturas/Valor/es_ES'] from catalog('"+catalogoAsignaturas+"') " +
					" where (item['Asignaturas/Pais'] ='"+pais+"' or item['Asignaturas/Pais'] ='GL' and item['Asignaturas/Visible'] = true)";
			SearchQuery searchQ = ctxPIM.createSearchQuery(sQuery);
			SearchResultSet resSet = searchQ.execute();
			valuesList = new String[resSet.size()];
			while(resSet.next()){
			
				valuesList[i] = resSet.getString(1);;
				i++;
			}
		
		}catch(PIMSearchException pse){
			pse.printStackTrace();
		}
		return valuesList;
	}

	public static String[] getMateriesValuesByCountry(String pais,
			String catalogoMaterias, String asignatura) {
		
		Context ctxPIM = PIMContextFactory.getCurrentContext();
		String[] valuesList = null;
		try{
			
			int i = 0;
			//Obtenemos las ediciones pertenecientes al pais		
			String sQuery = "select item['Materias/Valor/es_ES'] from catalog('"+catalogoMaterias+"') " +
					" where (item['Materias/Pais'] ='"+pais+"' or item['Materias/Pais'] ='GL' and item['Materias/Visible'] = true)";
			if (asignatura!=null && !asignatura.equals("")){
				Item itmAsig = getAsignaturaByName(asignatura, pais);
				if (itmAsig != null){
					sQuery = sQuery +" and item['Materias/Code_Asignatura'].pk = '"+itmAsig.getPrimaryKey() +"'";
				}
			}
			SearchQuery searchQ = ctxPIM.createSearchQuery(sQuery);
			SearchResultSet resSet = searchQ.execute();
			valuesList = new String[resSet.size()];
			while(resSet.next()){
			
				valuesList[i] = resSet.getString(1);;
				i++;
			}
		
		}catch(PIMSearchException pse){
			pse.printStackTrace();
		}
		return valuesList;
	}

	public static String[] getCursosValueByCountry(String pais,
			String catalogoCursos) {
		
		Context ctxPIM = PIMContextFactory.getCurrentContext();
		String[] valuesList = null;
		try{
			
			int i = 0;
			//Obtenemos las ediciones pertenecientes al pais		
			String sQuery = "select item['Cursos/Valor/es_ES'] from catalog('"+catalogoCursos+"') " +
					" where (item['Cursos/Pais'] ='"+pais+"' or item['Cursos/Pais'] ='GL' and item['Cursos/Visible'] = true) order by item['Cursos/Orden']";
			SearchQuery searchQ = ctxPIM.createSearchQuery(sQuery);
			SearchResultSet resSet = searchQ.execute();
			valuesList = new String[resSet.size()];
			while(resSet.next()){
			
				valuesList[i] = resSet.getString(1);;
				i++;
			}
		
		}catch(PIMSearchException pse){
			pse.printStackTrace();
		}
		return valuesList;
	}
	
	public static Item getGlobalItemByName(String campName, String catalogName){
		Item itm = null;
		Context ctxPIM = PIMContextFactory.getCurrentContext();
		try{
			
			//Obtenemos las ediciones pertenecientes al pais		
			String sQuery = "select item from catalog('"+catalogName+"')" +
					" where item['Tabla Global/Valor/es_ES'] = '"+campName+"'";
			SearchQuery searchQ = ctxPIM.createSearchQuery(sQuery);
			SearchResultSet resSet = searchQ.execute();
			if(resSet.next()){
			
				itm = resSet.getItem(1);
				
			}
		
		}catch(PIMSearchException pse){
			pse.printStackTrace();
		}
		return itm;
	}
	public static Item getSpecificItemByName(String value, String catalogName, String country){
		Item itm = null;
		Context ctxPIM = PIMContextFactory.getCurrentContext();
		try{
			
			//Obtenemos las ediciones pertenecientes al pais		
			String sQuery = "select item from catalog('"+catalogName+"') " +
					" where (item['Tabla Especifica/Pais'] ='"+country+"' or item['Tabla Especifica/Pais'] ='GL') and  item['Tabla Especifica/Valor/es_ES'] = '" + value +"' and item['Tabla Especifica/Visible'] = true";
			SearchQuery searchQ = ctxPIM.createSearchQuery(sQuery);
			SearchResultSet resSet = searchQ.execute();
			if(resSet.next()){
			
				itm = resSet.getItem(1);
				
			}
		
		}catch(PIMSearchException pse){
			pse.printStackTrace();
		}
		return itm;
	}
	public static Item getAsignaturaByName(String asignaturaName, String country){
		Item itm = null;
		Context ctxPIM = PIMContextFactory.getCurrentContext();
		try{
			
			//Obtenemos las ediciones pertenecientes al pais		
			String sQuery = "select item from catalog('Asignaturas') " +
					" where item['Asignaturas/Valor/es_ES'] = '"+asignaturaName+"'" +
							" and item['Asignaturas/Pais'] ='"+country+"'";
			SearchQuery searchQ = ctxPIM.createSearchQuery(sQuery);
			SearchResultSet resSet = searchQ.execute();
			if(resSet.next()){
			
				itm = resSet.getItem(1);
				
			}
		
		}catch(PIMSearchException pse){
			pse.printStackTrace();
		}
		return itm;
	}
	
	public static Item getLineaByName(String sLinea){
		Item itm = null;
		Context ctxPIM = PIMContextFactory.getCurrentContext();
		try{
			
			//Obtenemos las ediciones pertenecientes al pais		
			String sQuery = "select item from catalog('Lineas') " +
					" where item['Tabla Global/Valor/es_ES'] = '"+sLinea+"' order by item['Tabla Global/Code'] ";
			SearchQuery searchQ = ctxPIM.createSearchQuery(sQuery);
			SearchResultSet resSet = searchQ.execute();
			if(resSet.next()){
			
				itm = resSet.getItem(1);
				
			}
		
		}catch(PIMSearchException pse){
			pse.printStackTrace();
		}
		return itm;
	}
	
public static Item getCursoByName(String sCurso, String country) {

		System.out.println(sCurso);
		Context ctxPIM = PIMContextFactory.getCurrentContext();
		String[] valuesList = null;
		Item itm = null;
		try{
			
			int i = 0;
			//Obtenemos las ediciones pertenecientes al pais		
			String sQuery = "select item from catalog('Cursos') " +
					" where ((item['Cursos/Pais'] ='"+country+"' or item['Cursos/Pais'] ='GL') and item['Cursos/Visible'] = true and item['Cursos/Valor/es_ES'] = '"+ sCurso +"')";
			SearchQuery searchQ = ctxPIM.createSearchQuery(sQuery);
			SearchResultSet resSet = searchQ.execute();
			valuesList = new String[resSet.size()];
			while(resSet.next()){
			
				itm = resSet.getItem(1);
				i++;
			}
		
		}catch(PIMSearchException pse){
			pse.printStackTrace();
		}
		return itm;
	
		
	}
	public static Item getCicloByName(String sCiclo, String country) {

		Context ctxPIM = PIMContextFactory.getCurrentContext();
		Item itm = null;
		try{
			
			//Obtenemos las ediciones pertenecientes al pais		
			String sQuery = "select item from catalog('Ciclos') " +
					" where ((item['Ciclos/Pais'] ='"+country+"' or item['Ciclos/Pais'] ='GL') and item['Ciclos/Visible'] = true and item['Ciclos/Valor/es_ES'] = '"+ sCiclo +"')";
			SearchQuery searchQ = ctxPIM.createSearchQuery(sQuery);
			SearchResultSet resSet = searchQ.execute();
			while(resSet.next()){
			
				itm = resSet.getItem(1);
			}
		
		}catch(PIMSearchException pse){
			pse.printStackTrace();
		}
		return itm;

	}
	public static Item getNivelByName(String sNivel, String country) {

		Context ctxPIM = PIMContextFactory.getCurrentContext();
		Item itm = null;
		try{
			
			//Obtenemos las ediciones pertenecientes al pais		
			String sQuery = "select item from catalog('Niveles') " +
					" where ((item['Niveles/Pais'] ='"+country+"' or item['Niveles/Pais'] ='GL') and item['Niveles/Visible'] = true and item['Niveles/Valor/es_ES'] = '"+ sNivel +"')";
			SearchQuery searchQ = ctxPIM.createSearchQuery(sQuery);
			SearchResultSet resSet = searchQ.execute();
			while(resSet.next()){
			
				itm = resSet.getItem(1);
			}
		
		}catch(PIMSearchException pse){
			pse.printStackTrace();
		}
		return itm;

	}
	public static Item getSerieMetodoByName(String sSerie, String country) {

		Context ctxPIM = PIMContextFactory.getCurrentContext();
		Item itm = null;
		try{
			
			//Obtenemos las ediciones pertenecientes al pais		
			String sQuery = "select item from catalog('Series_Metodos') " +
					" where ((item['Series_Metodos/Pais'] ='"+country+"' or item['Series_Metodos/Pais'] ='GL') and item['Series_Metodos/Visible'] = true and item['Series_Metodos/Valor/es_ES'] = '"+ sSerie +"')";
			SearchQuery searchQ = ctxPIM.createSearchQuery(sQuery);
			SearchResultSet resSet = searchQ.execute();
			if(resSet.next()){
				itm = resSet.getItem(1);
			}
		
		}catch(PIMSearchException pse){
			pse.printStackTrace();
		}
		return itm;

	}
	public static Item getTemasByName(String sTema) {

		Context ctxPIM = PIMContextFactory.getCurrentContext();
		Item itm = null;
		try{
			
			//Obtenemos las ediciones pertenecientes al pais		
			String sQuery = "select item from catalog('Temas_Transversales') " +
					" where (item['Temas_Transversales/Visible'] = true and item['Temas_Transversales/Valor/es_ES'] = '"+ sTema +"')";
			SearchQuery searchQ = ctxPIM.createSearchQuery(sQuery);
			SearchResultSet resSet = searchQ.execute();
			if(resSet.next()){
				itm = resSet.getItem(1);
			}
		
		}catch(PIMSearchException pse){
			pse.printStackTrace();
		}
		return itm;

	}
	public static Item getMateriaByName(String materiaName, String country){
		Item itm = null;
		Context ctxPIM = PIMContextFactory.getCurrentContext();
		try{
			
			//Obtenemos las ediciones pertenecientes al pais		
			String sQuery = "select item from catalog('Materias') " +
					" where item['Materias/Valor/es_ES'] = '"+materiaName+"'" +
							" and item['Materias/Pais'] ='"+country+"'";
			SearchQuery searchQ = ctxPIM.createSearchQuery(sQuery);
			SearchResultSet resSet = searchQ.execute();
			if(resSet.next()){
			
				itm = resSet.getItem(1);
				
			}
		
		}catch(PIMSearchException pse){
			pse.printStackTrace();
		}
		return itm;
	}
	
	public static Item getPaisesByName(String pais){
		Item itm = null;
		Context ctxPIM = PIMContextFactory.getCurrentContext();
		try{
			
			//Obtenemos las ediciones pertenecientes al pais		
			String sQuery = "select item from catalog('Paises') " +
					" where item['Paises/Valor/es_ES'] = '"+pais+"'";
			SearchQuery searchQ = ctxPIM.createSearchQuery(sQuery);
			SearchResultSet resSet = searchQ.execute();
			if(resSet.next()){
			
				itm = resSet.getItem(1);
				
			}
		
		}catch(PIMSearchException pse){
			pse.printStackTrace();
		}
		return itm;
	}
	public static Item getIBICByName(String value){
		Item itm = null;
		Context ctxPIM = PIMContextFactory.getCurrentContext();
		try{
			
			//Obtenemos las ediciones pertenecientes al pais		
			String sQuery = "select item from catalog('IBIC') " +
					" where item['IBIC/Nombre/es_ES'] = '"+value+"'";
			SearchQuery searchQ = ctxPIM.createSearchQuery(sQuery);
			SearchResultSet resSet = searchQ.execute();
			if(resSet.next()){
			
				itm = resSet.getItem(1);
				
			}
		
		}catch(PIMSearchException pse){
			pse.printStackTrace();
		}
		return itm;
	}
	public static String getMoficationColAreaFromCountry(
			String countryCodeFromUser) {
		if (countryCodeFromUser != null){
			if (countryCodeFromUser.equals("AR")){
				return ConstSantillana.COL_AREA_MODIFI_AR;
				
			}
			if (countryCodeFromUser.equals("CO")){
				return ConstSantillana.COL_AREA_MODIFI_COL;
			}
			if (countryCodeFromUser.equals("CL")){
				return ConstSantillana.COL_AREA_MODIFI_CL;
				
			}
			if (countryCodeFromUser.equals("MX")){
				return ConstSantillana.COL_AREA_MODIFI_MX;
				
			}
		}
		
		return null;
	}

	public static Item getFechaByName(String sFecha, String country) {
		Item itm = null;
		Context ctxPIM = PIMContextFactory.getCurrentContext();
		try{
			
			//Obtenemos las ediciones pertenecientes al pais		
			String sQuery = "select item from catalog('Fechas_Conmemorativas') " +
					" where item['Fechas_Conmemorativas/Valor/es_ES'] = '"+sFecha+"'" +
							" and (item['Fechas_Conmemorativas/Pais'] ='"+country+"' or item['Fechas_Conmemorativas/Pais'] ='GL')";
			SearchQuery searchQ = ctxPIM.createSearchQuery(sQuery);
			SearchResultSet resSet = searchQ.execute();
			if(resSet.next()){
			
				itm = resSet.getItem(1);
				
			}
		
		}catch(PIMSearchException pse){
			pse.printStackTrace();
		}
		return itm;
	
	
	}

	public static Boolean isItemAvaibleInUserCountry(CollaborationItem itmCol) {
		Context ctxPIM = PIMContextFactory.getCurrentContext();
		
		String sCountry = getCountrysCodeFromUser(ctxPIM.getCurrentUser());
		System.out.println("sCountry " +sCountry );
		String[] aPaises = sCountry.split(";");
		Collection<Category> col =	itmCol.getCategories();
		for (Category cat:col) {
			String sPkCountry = cat.getParent().getPrimaryKey();
			System.out.println("sPkCountry " +sPkCountry );
			for (int i = 1; i < aPaises.length; i++) {
				
				
				String pais =  aPaises[i];
				System.out.println("pais " +pais );
				if (sPkCountry.equals(pais)) {
					System.out.println("return true ");;
					return true;
				}
			}
		}
		System.out.println("return false ");;
		return false;
		
	
	}

	public static Boolean isItemInDiferentsCountrys(CollaborationItem collabitem) {
		// TODO Auto-generated method stub

		System.out.println("Estoy en is diferentes conttrys");
		ArrayList<String> paises= new ArrayList<String>();
		Collection<Category> col =	collabitem.getCategories();
		for (Category cat:col) {
			if ((cat.getHierarchy().getName()).equals(ConstSantillana.JERARQUIA_PAISES)) {
				String sPkCountry = cat.getParent().getPrimaryKey();
				if (!paises.contains(sPkCountry)) {
					System.out.println("Pais que meto " + sPkCountry);
					paises.add(sPkCountry);
				}
			}
		}
		System.out.println("cuantos paises?" + paises.size());
		if (paises.size() > 1) {
			System.out.println("true");
			return true;
		}
		else {
			System.out.println("false");
			return false;
		}
	
	}
	
	public static Boolean isPack(Item item, String sSpecName){
		
		try{
			System.out.println("isPack?");
			AttributeInstance attInstancePacks =  item.getAttributeInstance(sSpecName + "/Packs");
			if(attInstancePacks!=null){
				System.out.println("...");
				List<AttributeInstance> packs = (List<AttributeInstance>) attInstancePacks.getChildren();
				if(packs!=null && packs.size()>0){
					System.out.println("OUUU YESSS");
					return true;
				}
			}
		}catch(UnsupportedOperationException uoe){
			return false;
		}catch(PIMInvalidPathException pipe){
			return false;
		}catch (PIMInternalException uoe) {
			return false;
		}catch (Exception e) {
			return false;
		}
		return false;
	}
		

}
